package com.ht.mq;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 通过阿里大于发送验证码
 */
@Component
@RocketMQMessageListener(topic = "phone_topic",consumerGroup = "topic_group")
public class MessageConsumer implements RocketMQListener<String> {

    @Autowired
    private RedisTemplate redisTemplate;

    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    @Override
    public void onMessage(String phone) {
        String randomNumbers = RandomUtil.randomNumbers(4);

        try{
            com.aliyun.dysmsapi20170525.Client client = MessageConsumer.createClient("LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName("东科创想")
                    .setTemplateCode("SMS_162522027")
                    .setTemplateParam("{\"sms_code\":\""+randomNumbers+"\"}");
            // 复制代码运行请自行打印 API 的返回值
            client.sendSms(sendSmsRequest);
        }catch (Exception e){
            e.printStackTrace();
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("phone_" + phone,randomNumbers);
        valueOperations.getAndExpire("phone_" + phone,100, TimeUnit.SECONDS);
    }
}
